package com.view;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bluetooth.Dispatcher;
import com.firewarning.R;

import org.w3c.dom.Text;
public class WarningActivity extends AppCompatActivity {
    private TextView thickness;
    private Button start;        //开始显示图形
    private Button stop;         //停止显示图形
    private Button change;      //改变阈值
    private EditText valueText; //用户输入的阈值
    private Dispatcher dispatcher = null;
    private SurfaceHolder holder;
    private Paint paint;
    final int HEIGHT = 500;    //画布高度
    final int X_OFFSET = 160;   //x轴的偏移
    private float cx = X_OFFSET; //  原点x坐标
    private float centerY = HEIGHT ; //原点Y坐标
    private float y=0;           //蓝牙传输的Y坐标
    private int count;
    private PaintThread paintThread;   //绘制线程
    private boolean isCome=false;//判断有没有数据到来
    private boolean isFirst=true;
    private Paint textPaint;
    private boolean isConnected=false;
    private boolean isStop=false;
    private boolean isPress=false;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1&&!isStop) {
                String data = (String) msg.obj;
                    thickness.setText(data+"mg/m3");
                    isCome=true;
                    y=Float.parseFloat(data);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_warning);
        //显示浓度的控件
        thickness=(TextView)this.findViewById(R.id.warning_thickness);
        thickness.setText("0mg/m3");
        //开始和停止按钮
        start=(Button)this.findViewById(R.id.start);
        stop=(Button)this.findViewById(R.id.stop);
        //事件监控器
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if(v.getId()==R.id.start){
                    Toast.makeText(WarningActivity.this, "开始显示", Toast.LENGTH_SHORT).show();
                    if(!isConnected) {
                        Intent intent = WarningActivity.this.getIntent();
                        String address = intent.getExtras().getString("address");
                        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                        dispatcher = new Dispatcher(bluetoothAdapter, address);
                        dispatcher.acceptMessage(WarningActivity.this, handler, Double.parseDouble("0.8"));
                        paintThread = new PaintThread();
                        new Thread(paintThread).start();
                        isConnected=true;
                    }else {
                       isStop=false;
                    }
                }else if(v.getId()==R.id.stop){
                    Toast.makeText(WarningActivity.this,"已停止显示",Toast.LENGTH_SHORT).show();
                  isStop=true;
                }
                //用来改变阈值
//                else if(v.getId()==R.id.warning_button_show){
//                    String value=valueText.getText().toString().trim();
//                    try{
//                        double valueDouble=Double.parseDouble(value);
//                        dispatcher.getAcceptThread().setValue( valueDouble);
//                        Toast.makeText(WarningActivity.this,"阈值已改变",Toast.LENGTH_SHORT).show();
//                    }catch (Exception e){
//                        Toast.makeText(WarningActivity.this,"请输入正确格式的数字",Toast.LENGTH_SHORT).show();
//                    }finally {
//                    }
//                }
            }
        };
        start.setOnClickListener(listener);
        stop.setOnClickListener(listener);
        //显示要绘制的画布
        final SurfaceView surfaceView = (SurfaceView) findViewById(R.id.show);
        //初始化SurfaceHolder对象
        holder = surfaceView.getHolder();
        paint = new Paint();
        paint.setColor(getResources().getColor(R.color.blue));
        paint.setStrokeWidth(5);
        textPaint=new Paint();
        textPaint.setTextSize(30);
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
            }
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                drawkBack(holder);
            }
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                    if(paintThread!=null){
                        paintThread.stop();
                        dispatcher.getAcceptThread().exit();
                    }
            }
        });
      //  change = (Button) findViewById(R.id.warning_button_show);
      //  change.setOnClickListener(listener);
        //valueText = (EditText) findViewById(R.id.warning_button_value);
//        valueText.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//              isStop=true;
//               isPress=true;
//            }
//        });
//
//        valueText.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//
//                if(hasFocus) {
//                 isStop=true;
//                 isPress=true;
//                } else {
//                   isStop=false;
// 此处为失去焦点时的处理内容

        //        }
        //    }
      //  });
    }

    /**
     * 清除画布
     */
    public void clearDraw() {
        Canvas canvas = null;
        try {
            canvas = holder.lockCanvas(null);
            canvas.drawColor(Color.WHITE);
        }catch (Exception e) {
            // TODO: handle exception
        }finally {
            if(canvas != null) {
                holder.unlockCanvasAndPost(canvas);
            }
        }
    }

    /**
     * 绘制背景
     * @param holder
     */
    private void drawkBack(SurfaceHolder holder) {
        Canvas canvas = holder.lockCanvas(null);
        //绘制白色背景
        canvas.drawColor(Color.WHITE);
        holder.unlockCanvasAndPost(canvas);
        holder.lockCanvas(new Rect(0, 0, 0, 0));
        holder.unlockCanvasAndPost(canvas);
    }
    public void onDestroy() {
        super.onDestroy();
        if (dispatcher != null) {
            dispatcher.getAcceptThread().exit();
            dispatcher.destory();
        }
    }
    class  PaintThread implements  Runnable{
        private boolean isRun=true;
        @Override
        public void run() {
            clearDraw();
            drawkBack(holder);
            cx = X_OFFSET;
            count = 0;
            while (isRun) {
                if (isCome&!isStop) {
                    isCome=false;
                    if (isFirst) {
                        Canvas canvas;
                        float cy = centerY - y*100;
                        canvas = holder.lockCanvas(new Rect((int) (cx - 20), (int) (cy - 20), (int) (cx + 20), (int) (centerY + 20)));
                        Paint paint = new Paint();
                        paint.setColor(Color.WHITE);
                        canvas.drawPoint(cx, cy, paint);
                        holder.unlockCanvasAndPost(canvas);
                        isFirst = false;
                    } else {
                        float cy = centerY - y*1000;
                        Canvas canvas;
                        canvas = holder.lockCanvas(new Rect((int) (cx - 70), (int) (cy - 70), (int) (cx + 70), (int) (centerY + 70)));
                        canvas.drawRect(new Rect((int) (cx - 10), (int) (cy), (int) (cx + 10), (int) (centerY)), paint);
                        canvas.drawText(""+y,cx-40,cy-20,textPaint);
                        holder.unlockCanvasAndPost(canvas);
                        cx += 150;
                        count++;
                        if (count > 6) {
                            cx = X_OFFSET;
                            count = 0;
                            clearDraw();
                            drawkBack(holder);
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        public void stop(){
            isRun=false;
            isFirst=true;
            isCome=false;

        }
    }

}


